package com.xzq.util;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.xzq.entity.Page;

@Component
public class HibernatePage<T> {
	@Resource
	protected HibernateTemplate template;
	public Page findHibernatePage(Page page,final String hql,final Object[] obj,int getPageSize) {
		String hqltou = "select count(*) ";
		@SuppressWarnings("rawtypes")
		List find = new ArrayList();
		String minHql =" "+ hql.toLowerCase();
		String lostHeadHql = hql.substring(minHql.indexOf(" from "));
		if(obj==null||obj.length==0){
			find = template.find(hqltou+lostHeadHql);
		}else{
			find = template.find(hqltou+lostHeadHql,obj);
		}
		Long num = (Long) find.get(0);
		int getallcount = (int) (num/1);
		page.setPageSize(getPageSize);
		page.setAllcount(getallcount);
		page.setAllpage(getallcount);
		final int pageSize = getPageSize;
		final int min = pageSize*(page.getNowpage()-1);
		List<T> list = template.execute(new HibernateCallback<List<T>>() {
			@SuppressWarnings("unchecked")
			@Override
			public List<T> doInHibernate(Session session)
					throws HibernateException {
				Query query = session.createQuery(hql);
				if(obj!=null&&obj.length!=0){
					for(int i=0;i<obj.length;i++){
						query.setParameter(i, obj[i]);
					}
				}
				query.setFirstResult(min);
				query.setMaxResults(pageSize);
				return query.list();
			}
		});
		page.setGetlist(list);
		return page;
	}
}
